<template>
  <div>
    <el-card>
      <div style="margin-top: 10px" class="btn">
        <div class="delete">
          <el-button @click="deleteBySelected()" type="primary">批量删除</el-button>
          <el-button @click="toggleSelection()">取消选择</el-button>
        </div>
        <!-- <div></div> -->
        <div class="search">
          <el-input
            placeholder="请输入关键词搜索"
            class="searchName"
            v-model="searchName"
            id="query"
            icon="el-icon-search"
            @input="query(searchName)"
            style="width:200px"
          ></el-input>
          <el-button @click="export2Excel" type="primary">导出资源信息</el-button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        border
        @selection-change="handleSelectionChange"
        :data="
      tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="resname" label="资源名称" width="360"></el-table-column>
        <el-table-column sortable prop="subid" label="科目" width="200"></el-table-column>
        <el-table-column sortable prop="spendtime" label="最少观看时间(分钟)" width="150"></el-table-column>
        <el-table-column sortable prop="uploadtime" label="上传时间" width="260"></el-table-column>
        <el-table-column sortable prop="isdownload" label="是否可下载" width="200"></el-table-column>
        <el-table-column sortable prop="isuse" label="是否必学" width="200"></el-table-column>
        <el-table-column fixed="right" label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleFileView(scope.$index, scope.row)">查看</el-button>
            <el-button
              type="text"
              size="small"
              @click="dialogFormVisible = true,handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              size="medium"
              icon="el-icon-download"
              @click="handleDownload(scope.$index, scope.row)"
            ></el-button>
            <el-button
              size="medium"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              icon="el-icon-delete"
              style="height:25px"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 40]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
      ></el-pagination>
      <el-dialog title="资源信息" :visible.sync="dialogFormVisible">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="资源名称" prop="resname" style="width:400px">
            <el-input v-model="ruleForm.resname" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="科目" prop="subid">
            <el-select v-model="ruleForm.subid" placeholder="请选择">
              <el-option
                v-for="item in subject"
                :key="item.subid"
                :label="item.subname"
                :value="item.subid"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="最少观看时间" prop="spendtime">
            <el-input-number
              v-model="ruleForm.spendtime"
              controls-position="right"
              @change="handleChange"
              :min="0"
              :max="180"
            ></el-input-number>分钟
          </el-form-item>
          <el-form-item label="是否可下载" prop="isdownload">
            <el-select v-model="ruleForm.isdownload" placeholder="请选择是否可下载">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否必学" prop="isuse">
            <el-select v-model="ruleForm.isuse" placeholder="请选择是否必学">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false,updateInfo()">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="预览"
        :visible.sync="viewVisible"
        width="100%"
        height="100%"
        :before-close="closeDialog"
      >
        <div class="pdf" v-show="fileType === 'pdf'">
          <pdf :src="pdfsrc"></pdf>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// import "@/mock/file";
import axios from "axios";
import Message from "@/plugins/message";
export default {
  methods: {
    handleClick(row) {
      console.log(row);
    }
  },

  data() {
    return {
      num: 1,
      tableData: [],
      secondData: [],
      currentPage: 1, //初始页
      pagesize: 10, //    每页的数据
      searchName: "",
      dialogFormVisible: false,
      subject: [],
      subname: "",
      ruleForm: {
        resid: "",
        subid: "",
        resname: "",
        path: "",
        spendtime: 0,
        uploadtime: "",
        isuse: "",
        isdownload: ""
      },
      rules: {
        resname: [
          { required: true, message: "请输入资源名称", trigger: "blur" }
        ],
        spendtime: [
          { required: true, message: "请输入最少观看时间", trigger: "blur" }
        ],
        isdownload: [
          { required: true, message: "请选择是否下载", trigger: "change" }
        ],
        isuse: [{ required: true, message: "请选择是否必学", trigger: "blur" }]
      },
      options: [
        {
          dept: "选项1",
          label: "信息科学与工程学院"
        },
        {
          dept: "选项2",
          label: "软件学院"
        },
        {
          dept: "选项3",
          label: "外国语学院"
        },
        {
          dept: "选项4",
          label: "数学学院"
        },
        {
          dept: "选项5",
          label: "物理学院"
        }
      ],
      viewVisible: false, // 弹框隐藏
      pdfsrc: "",
      fileType: "pdf",
      globalPath: "http://localhost:8080/"
    };
  },
  created() {
    axios.get("/subSelectAll").then(res => {
      let { code, message, data } = res.data;
      // console.log(data);
      let len = data.length;
      for (let i = 0; i < len; i++) {
        let sub = { subname: data[i].subname, subid: data[i].subid };
        this.subject.push(sub);
      }
    });
    this.queryFile();
  },
  methods: {
    handleFileView(index, row) {
      if (row.type != "pdf" && row.type != "PDF") {
        // 不是pdf格式
        window.open(this.globalPath + row.path);
        return false;
      } else {
        // pdf 格式
        let url = this.globalPath + row.path;
        this.viewVisible = true;
        this.pdfsrc = url;
      }
    },
    closeDialog(done) {
      done();
    },
    handleDownload(index, row) {
      console.log(index, row);

      // var elemIF = document.createElement('iframe')
      // elemIF.src = row.path;
      // elemIF.style.display = 'none'
      // document.body.appendChild(elemIF)
    //    let xhr = new XMLHttpRequest()
    // xhr.open('post',this.globalPath + "download")
    // //如果需要请求头中这是token信息可以在这设置
    // xhr.setRequestHeader('Content-Type','application/json;charset=UTF-8')
    // xhr.responseType = 'blob'
    // xhr.send(JSON.stringify({resid:row.resid}))
    // xhr.onreadystatechange = function(){
    //   if(xhr.readyState ===4 && xhr.status === 200){
    //     const blob = new Blob([xhr.response])
    //     let url = window.URL.createObjectURL(blob)
  
    //     //创建一个a标签元素，设置下载属性，点击下载，最后移除该元素
    //     let link = document.createElement('a')
    //     link.href = url
    //     link.style.display = 'none'
    //     //取出下载文件名
    //     const fileName = xhr.getResponseHeader('filename')
    //     const downlaodFileName = decodeURIComponent(fileName)
  
    //     link.setAttribute('download',downlaodFileName)
    //     link.click()
    //     window.URL.revokeObjectURL(url)
    //   }
    axios({
      url:"/download",
      method:"get",
      params:{
        resid:row.resid
      },
      responseType:'blob'
    }).then(res=>{
      // console.log(res.data);
      const blob = new Blob([res.data])
      console.log(res.headers["content-disposition"])
      let url = window.URL.createObjectURL(blob)

      //创建一个a标签元素，设置下载属性，点击下载，最后移除该元素
      let link = document.createElement('a')
      link.href = url
      link.style.display = 'none'
      //res.headers.fileName 取出后台返回下载的文件名
      const downlaodFileName = decodeURIComponent(res.headers.filename)
      // console.log(downlaodFileName);
      link.setAttribute('download',row.resname + "." + row.type)
      link.click()
      window.URL.revokeObjectURL(url)
    });

    },
    updateInfo(value) {
      // console.log(this.ruleForm);
      let that = this;
      let obj = {
        resid: that.ruleForm.resid,
        rename: that.ruleForm.resname,
        spendtime: that.ruleForm.spendtime,
        isuse: that.ruleForm.isuse === "必学" ? true : false,
        isdownload: that.ruleForm.isdownload === "是" ? true : false
      };
      axios({
        method: "post",
        url: "file/update",
        data: obj
      }).then(res => {
        console.log(res.data);
      });
    },
    handleChange(value) {
      console.log(value);
    },
    transferDate(time) {
      let d = new Date(time);
      return (
        d.getFullYear() +
        "-" +
        (d.getMonth() + 1) +
        "-" +
        d.getDate() +
        " " +
        (d.getHours() < 10 ? "0" + d.getHours() : d.getHours()) +
        ":" +
        (d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes()) +
        ":" +
        (d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds())
      );
    },
    querySub(item) {
      for (let i = 0; i < this.subject.length; i++) {
        if (this.subject[i].subid === item.subid) {
          return this.subject[i].subname;
        }
      }
    },
    queryFile: function() {
      axios.post("/file/queryAll").then(res => {
        let data = res.data.data;
        console.log(data);
        // console.log(this.subject);
        data.forEach(item => {
          item.uploadtime += "";
          item.uploadtime = this.transferDate(item.uploadtime);
          // this.subject.forEach(sub => {
          //   if(sub.subid === item.subid){
          //     item.subid = sub.subname;
          //   }
          // })
          item.subid = this.querySub(item);
          if (item.isdownload === true) {
            item.isdownload = "是";
          } else {
            item.isdownload = "否";
          }
          if (item.isuse === true) {
            item.isuse = "必学";
          } else {
            item.isuse = "选学";
          }
        });
        console.log(data);
        this.tableData = data;
        this.secondData = data;
      });
    },

    handleSizeChange: function(size) {
      this.pagesize = size;
      console.log(this.pagesize); //每页下拉显示数据
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage;
      console.log(this.currentPage); //点击第几页
    },
    handleDelete(index, row) {
      console.log(row.teano);
      axios({
        url: "file/deleteBySelected",
        params: {
          resid: row.resid
        }
      }).then(res => {
        const { code, message, data } = res.data;
        console.log(res.data);
        if (code === 200) {
          Message.success(message);
          this.tableData.splice(index, 1);
        } else {
          Message.error(message);
        }
      });
    },
    handleEdit(index, row) {
      this.ruleForm.resid = row.resid;
      this.ruleForm.resname = row.resname;
      this.ruleForm.path = row.path;
      this.ruleForm.spendtime = row.spendtime;
      this.ruleForm.uploadtime = row.uploadtime;
      this.ruleForm.isdownload = row.isdownload;
      this.ruleForm.isuse = row.isuse;
    },

    query(searchName) {
      let search = this.searchName;
      this.tableData = this.secondData;
      this.tableData = this.tableData.filter(
        data =>
          data.resname.toLowerCase().includes(search.toLowerCase()) ||
          data.uploadtime.toLowerCase().includes(search.toLowerCase()) ||
          data.isuse.toLowerCase().includes(search.toLowerCase()) ||
          data.isdownload.toLowerCase().includes(search.toLowerCase()) ||
          data.spendtime.toLowerCase().includes(search.toLowerCase())
      );
    },
    toggleSelection() {
      // if (rows) {
      //   rows.forEach(row => {
      //     this.$refs.multipleTable.toggleRowSelection(row);
      //   });
      // } else {
      this.$refs.multipleTable.clearSelection();
      // }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    deleteBySelected: function() {
      let vm = this;
      var resids = this.multipleSelection.map(item => item.resid); //获取所有选中行的id组成的字符串，以逗号分隔
      console.log(resids);
      // axios.post("file/deleteBySelected", { resids }).then(res => {
      //   const { code, msg, result } = res.data;
      //   console.log(res.data);
      //   if (code === 0) {
      //     for (let i = 0; i < result.length; i++) {
      //       for (let j = 0; j < vm.tableData.length; j++) {
      //         if (result[i] === vm.tableData[j].resid) {
      //           vm.tableData.splice(j, 1);
      //         }
      //       }
      //     }
      //     Message.success(msg);
      //     // this.tableData = adminData;
      //   }
      // });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    export2Excel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require("@/vendor/Export2Excel");
        const tHeader = [
          "资源名称",
          "最少观看时间",
          "上传时间",
          "是否可下载",
          "是否必学"
        ];
        const filterVal = [
          "resname",
          "spendtime",
          "uploadtime",
          "isdownload",
          "isuse"
        ];
        const list = this.tableData;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "资源信息列表");
      });
    }
  }
};
</script>
<style scoped>
/* *{
  margin :0;
  padding: 0;
} */
/* .btn .search */
.btn {
  display: flex;
  justify-content: space-between;
  /* justify-content: space-between */
  /* border: 1px solid black; */
}
.delete {
  /* width: 50%; */
  /* border: 1px solid black; */
}
.btn .search {
  /* width: 20%; */
  /* border: 1px solid black; */
}
</style>
